package com.cloud.auth.controller;

import com.alibaba.fastjson.JSON;
import com.cloud.auth.service.UserService;
import com.cloud.auth.util.ApiResult;
import com.cloud.auth.util.MapUtil;
import com.cloud.auth.util.RedisUtil;
import com.cloud.auth.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @packageName: com.api.controller.auth
 * @name: LoginController
 * @description:
 * @author: 董定卓
 * @dateTime: 2019/6/14 10:49
 */
@RestController
public class LoginController {

    @Autowired
    UserService service;

    /**
     * 用户登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public ApiResult login(@RequestParam Map<String, Object> map) {
        String account = MapUtil.getString(map, "account");
        if (account == null) {
            return ApiResult.failResult("登录账号不能为空");
        }
        String password = MapUtil.getString(map, "password");
        if (password == null) {
            return ApiResult.failResult("登录密码不能为空");
        }
        Map<String, Object> user = service.login(map);
        if (user == null) {
            return ApiResult.failResult("登录失败,账号或密码错误");
        }
        if ("0".equals(user.get("state").toString())) {
            return ApiResult.failResult("账号无效,请联系管理员");
        }
        //获取用户菜单
        List<Map<String, Object>> userPermissionList = service.listPermissionByUserId(user.get("id").toString());
        List<Map<String, Object>> userMenuList = new ArrayList<>();
        for (Map<String, Object> userPermissionMap : userPermissionList) {
            String menu = userPermissionMap.get("menu").toString();
            if ("0".equals(menu)) {
                break;
            }
            userMenuList.add(userPermissionMap);
        }
        //获取权限代码(用户前端控制)和权限URL(用户后端请求拦截)
        List<String> permissionCodes = new ArrayList<>();
        List<String> permissionUrls = new ArrayList<>();
        for (Map<String, Object> userPermission : userPermissionList) {
            permissionCodes.add(userPermission.get("code").toString());
            permissionUrls.add(userPermission.get("url").toString());
        }
        String token = TokenUtil.generate(account, password);

        user.put("menu", getChildren(userMenuList, "-1"));
        user.put("permissionCodes", permissionCodes);
        user.put("token", token);
        user.put("permissionUrls", permissionUrls);

        RedisUtil.setString(token, JSON.toJSONString(user), 1, TimeUnit.HOURS);

        return ApiResult.successResultForData(user);
    }

    /**
     * 退出
     *
     * @param map
     */
    @PostMapping("/logout")
    public ApiResult logout(@RequestParam Map<String, Object> map) {
        RedisUtil.delete(map.get("token").toString());
        return ApiResult.successResult();
    }


    private List<Map<String, Object>> getChildren(List<Map<String, Object>> list, String fid) {
        List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
        for (int j = 0; j < list.size(); j++) {
            Map<String, Object> map = null;
            Map<String, Object> treeChild = list.get(j);
            String parentId = treeChild.get("parentId").toString();
            if (parentId.equals(fid)) {
                map = new HashMap<>();
                String id = treeChild.get("id").toString();
                map.put("id", id);
                map.put("title", treeChild.get("name"));
                map.put("href", treeChild.get("url"));
                boolean ownChildren = (long) treeChild.get("ownChildren") > 0;
                map.put("spread", ownChildren);
                map.put("children", getChildren(list, id));
            }
            if (map != null) {
                childList.add(map);
            }
        }
        return childList;
    }
}
